//
// Source code recreated from ConfigVo .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ht.modules.system.online.cgreport.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.modules.system.online.cgreport.entity.OnlCgreportHead;
import com.ht.modules.system.online.cgreport.entity.OnlCgreportItem;
import com.ht.modules.system.online.cgreport.entity.OnlCgreportParam;
import com.ht.modules.system.online.cgreport.service.IOnlCgreportHeadService;
import com.ht.modules.system.online.cgreport.service.IOnlCgreportItemService;
import com.ht.modules.system.online.cgreport.service.IOnlCgreportParamService;
import com.ht.modules.system.online.cgreport.util.CgReportQueryParamUtil;
import com.ht.modules.system.online.cgreport.util.SqlUtil;
import com.ht.api.ISysBaseAPI;
import com.ht.entity.DictModel;
import com.ht.entity.Result;
import com.ht.exception.JeecgBootException;
import com.ht.utils.BrowserUtils;
import com.ht.utils.oConvertUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping({"/online/cgreport/api"})
public class OnlCgreportAPI {
    private static final Logger log = LoggerFactory.getLogger(OnlCgreportAPI.class);
    @Autowired
    private IOnlCgreportHeadService onlCgreportHeadService;
    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;

    public OnlCgreportAPI() {
    }

    @GetMapping({"/getColumns/{code}"})
    public Result<?> getColumns(@PathVariable("code") String code) {
        OnlCgreportHead head = (OnlCgreportHead)this.onlCgreportHeadService.getById(code);
        if (head == null) {
            return Result.error("实体不存在");
        } else {
            QueryWrapper<OnlCgreportItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cgrhead_id", code);
            queryWrapper.eq("is_show", 1);
            queryWrapper.orderByAsc(Arrays.toString(new String[]{"order_num"}));
            List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);
            List<Map<String, String>> array = new ArrayList<>();
            Map<String, Object> dictOptions = new HashMap<>();

            for (OnlCgreportItem item : list) {
                Map<String, String> column = new HashMap<>(3);
                column.put("title", item.getFieldTxt());
                column.put("dataIndex", item.getFieldName());
                column.put("align", "center");
                column.put("sorter", "true");
                array.add(column);
                String dictCode = item.getDictCode();
                if (oConvertUtils.isNotEmpty(dictCode)) {
                    List<DictModel> ls = this.sysBaseAPI.queryDictItemsByCode(dictCode);
                    dictOptions.put(item.getFieldName(), ls);
                    column.put("customRender", item.getFieldName());
                }
            }

            Map<String, Object> result = new HashMap<>(1);
            result.put("columns", array);
            result.put("dictOptions", dictOptions);
            result.put("cgreportHeadName", head.getName());
            return Result.ok(result);
        }
    }

    @GetMapping({"/getData/{code}"})
    public Result<?> getData(@PathVariable("code") String code, HttpServletRequest request) {
        OnlCgreportHead head = this.onlCgreportHeadService.getById(code);
        if (head == null) {
            return Result.error("实体不存在");
        } else {
            String sql = head.getCgrSql();

            try {
                Map<String, Object> params = SqlUtil.getParameterMap(request);
                params.put("onlCgreportHeadId", head.getId());
                Map<String, Object> reslutMap = this.onlCgreportHeadService.executeSelectSql(sql, params);
                return Result.ok(reslutMap);
            } catch (Exception var7) {
                log.error(var7.getMessage(), var7);
                return Result.error("SQL执行失败：" + var7.getMessage());
            }
        }
    }

    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> getQueryInfo(@PathVariable("code") String cgrheadId) {
        try {
            List<Map<String, String>> list = this.onlCgreportItemService.getAutoListQueryInfo(cgrheadId);
            return Result.ok(list);
        } catch (Exception var3) {
            log.info(var3.getMessage(), var3);
            return Result.error("查询失败");
        }
    }

    @GetMapping({"/getParamsInfo/{code}"})
    public Result<?> getParamsInfo(@PathVariable("code") String cgrheadId) {
        try {
            LambdaQueryWrapper<OnlCgreportParam> query = new LambdaQueryWrapper();
            query.eq(OnlCgreportParam::getCgrheadId, cgrheadId);
            List<OnlCgreportParam> list = this.onlCgreportParamService.list(query);
            return Result.ok(list);
        } catch (Exception var4) {
            log.info(var4.getMessage(), var4);
            return Result.error("查询失败");
        }
    }

    @RequestMapping({"/exportXls/{reportId}"})
    public void exportXls(@PathVariable("reportId") String reportId, HttpServletRequest request, HttpServletResponse response) {
        String codedFileName = "报表";
        String sheetName = "导出信息";
        if (oConvertUtils.isNotEmpty(reportId)) {
            Map cgReportMap = null;

            try {
                cgReportMap = this.onlCgreportHeadService.queryCgReportConfig(reportId);
            } catch (Exception var35) {
                throw new JeecgBootException("动态报表配置不存在!");
            }

            List<Map<String, Object>> fieldList = (List)cgReportMap.get("items");
            Map<String, Object> configM = (Map)cgReportMap.get("main");
            codedFileName = configM.get("name") + codedFileName;
            String querySql = (String)configM.get("cgreport_sql");
            List<Map<String, Object>> items = (List)cgReportMap.get("items");
            List<String> paramList = (List)cgReportMap.get("params");
            Map<String, Object> pageSearchFields = new LinkedHashMap<>();
            Map<String, Object> paramData = new HashMap<>();
            Iterator<?> var14;
            String isQuery;
            if (paramList != null && !paramList.isEmpty()) {
                var14 = paramList.iterator();

                while(var14.hasNext()) {
                    String param = (String)var14.next();
                    isQuery = request.getParameter(param);
                    isQuery = isQuery == null ? "" : isQuery;
                    querySql = querySql.replace("'${" + param + "}'", ":" + param);
                    querySql = querySql.replace("${" + param + "}", ":" + param);
                    paramData.put(param, isQuery);
                }
            }

            var14 = items.iterator();

            while(var14.hasNext()) {
                Map<String, Object> item = (Map)var14.next();
                isQuery = item.get("search_flag").toString();
                if ("Y".equalsIgnoreCase(isQuery)) {
                    CgReportQueryParamUtil.loadQueryParams(request, item, pageSearchFields, paramData);
                }
            }

            String dbKey = (String)configM.get("db_source");
            List<Map<?, ?>> result = null;
            if (oConvertUtils.isNotEmpty(dbKey)) {
                if (!paramData.isEmpty()) {
                }
            } else {
                result = this.onlCgreportHeadService.queryByCgReportSql(querySql, pageSearchFields, paramData, -1, -1);
            }

            List<ExcelExportEntity> entityList = new ArrayList<>();

            for(int i = 0; i < fieldList.size(); ++i) {
                if ("1".equals(oConvertUtils.getString(((Map)fieldList.get(i)).get("is_show")))) {
                    ExcelExportEntity expEntity = new ExcelExportEntity(((Map)fieldList.get(i)).get("field_txt").toString(), ((Map)fieldList.get(i)).get("field_name"), 15);
                    Object dictCode = ((Map)fieldList.get(i)).get("dict_code");
                    if (oConvertUtils.isNotEmpty(dictCode)) {
                        List<String> dictReplaces = new ArrayList<>();
                        List<DictModel> dictList = this.sysBaseAPI.queryDictItemsByCode(dictCode.toString());
                        Iterator var22 = dictList.iterator();

                        while(var22.hasNext()) {
                            DictModel d = (DictModel)var22.next();
                            dictReplaces.add(d.getText() + "_" + d.getValue());
                        }

                        expEntity.setReplace((String[])dictReplaces.toArray(new String[dictReplaces.size()]));
                    }

                    Object replace_val = ((Map)fieldList.get(i)).get("replace_val");
                    if (oConvertUtils.isNotEmpty(replace_val)) {
                        expEntity.setReplace(replace_val.toString().split(","));
                    }

                    entityList.add(expEntity);
                }
            }

            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream fOut = null;

            try {
                String browse = BrowserUtils.checkBrowse(request);
                if ("MSIE".equalsIgnoreCase(browse.substring(0, 4))) {
                    response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(codedFileName, "UTF-8") + ".xls");
                } else {
                    String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls");
                }

                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams((String)null, sheetName), entityList, result);
                fOut = response.getOutputStream();
                workbook.write(fOut);
            } catch (Exception var33) {
            } finally {
                try {
                    fOut.flush();
                    fOut.close();
                } catch (Exception var32) {
                }

            }

        } else {
            throw new JeecgBootException("参数错误");
        }
    }

    @GetMapping({"/getRpColumns/{code}"})
    public Result<?> getRpColumns(@PathVariable("code") String code) {
        LambdaQueryWrapper<OnlCgreportHead> query = new LambdaQueryWrapper();
        query.eq(OnlCgreportHead::getCode, code);
        OnlCgreportHead head = (OnlCgreportHead)this.onlCgreportHeadService.getOne(query);
        if (head == null) {
            return Result.error("实体不存在");
        } else {
            QueryWrapper<OnlCgreportItem> queryWrapper = new QueryWrapper();
            queryWrapper.eq("cgrhead_id", head.getId());
            queryWrapper.eq("is_show", 1);
            queryWrapper.orderByAsc(Arrays.asList("order_num"));
            List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);
            List<Map<String, String>> array = new ArrayList<>();
            Map<String, Object> dictOptions = new HashMap();

            HashMap column;
            for(Iterator var8 = list.iterator(); var8.hasNext(); array.add(column)) {
                OnlCgreportItem item = (OnlCgreportItem)var8.next();
                column = new HashMap(3);
                column.put("title", item.getFieldTxt());
                column.put("dataIndex", item.getFieldName());
                column.put("align", "center");
                String dbtype = item.getFieldType();
                if ("Integer".equals(dbtype) || "Date".equals(dbtype) || "Long".equals(dbtype)) {
                    column.put("sorter", "true");
                }

                String dictCode = item.getDictCode();
                if (oConvertUtils.isNotEmpty(dictCode)) {
                    List<DictModel> ls = this.sysBaseAPI.queryDictItemsByCode(dictCode);
                    dictOptions.put(item.getFieldName(), ls);
                    column.put("customRender", item.getFieldName());
                }
            }

            Map<String, Object> result = new HashMap(1);
            result.put("columns", array);
            result.put("dictOptions", dictOptions);
            result.put("cgRpConfigId", head.getId());
            result.put("cgRpConfigName", head.getName());
            return Result.ok(result);
        }
    }
}
